<template>
    <!-- 营销项目计划审核 -->
    <div>
        <!-- 搜索 -->
        <TopFilter
            ref="commonTopFilter"
            :list="topFilterInit"
            :cols="3"
            labelWidth="90"
            @filterChange="changeHandle"
            @onCollapse="collapseHandle"
        ></TopFilter>
        <!-- 列表 -->
        <FilterTable
            ref="table"
            :columns="columns"
            :fetchapi="fetchApi"
            :params="fetchParams"
            :datakey="'records'"
            :isSelectColumn="true"
            :selectionType="'multiple'"
            :onRowSelectChange="selectChange"
            :onCellChange="onCellChange"
            :onColumnsChange="columns => this.columns = columns"
            columnsRef="projectOperating_plan_planFirstCheck_index_01"
        >
            <template slot="controls">
                <el-button size="small" type="primary" icon="el-icon-check" @click="batchPass()">批量通过</el-button>
                <el-button size="small" type="primary" icon="el-icon-close" @click="batchReject()">批量驳回</el-button>
                <el-button size="small" type="primary" icon="el-icon-download" @click="doExportExcel()">下载</el-button>
            </template>
        </FilterTable>
        <!-- 弹窗 -->
        <!-- 选择车型 -->
        <BaseDialog
            title="选择车型"
            :visible.sync="visibleDialog"
            width="700px"
            destroyOnClose
            :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
            >
            <infoModal selectType="multiple" @close="selectModelBack" />
        </BaseDialog>
        <!-- 选择方案 -->
        <BaseDialog
            title="选择项目"
            :visible.sync="visibleDialogPro"
            width="700px"
            destroyOnClose
            :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
            >
            <programModal selectType="single" @close="selectModelBackPro" />
        </BaseDialog>
        <!-- 经销商弹窗 -->
        <BaseDialog
            title="经销商查询"
            :visible.sync="visibleDealer"
            width="1000px"
            destroyOnClose
            :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
        >
        <dealer-madal
            ref='dealerDialog'
            :deptId="orgId"
            :dealerType="dealerType"
            selectType='single'
            v-model="initDealerData"
            @close="closeDealer"
        />
        </BaseDialog>
        <BaseDialog
            title="审核意见"
            :visible.sync="visible"
            width="400px"
            destroyOnClose
            :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}" >
            <checkDialog   @close="dialogClose" />
        </BaseDialog>
        <Drawer
            ref="infoDrawer"
            :visible.sync="visibleDrawer"
            title="项目计划信息"
            destroyOnClose
            :containerStyle="{width:'70vw',height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
        >
            <details-form :options="detailsConfig" @close="closeDrawer"/>
        </Drawer>
    </div>
</template>

<script>

    import { dictionary } from '@/utils/dictMixin';
    import { region } from '@/api/cms-common/region';
    // import { getLoginUser } from '@/api/cms-api/projectOperating/program/departmentInquire'; //获取登录信息
    // import dealerMadal from '@/pages/cms-common/dealerdata'
    import dealerMadal from '@/pages/cms-common/dealerdata/dealerType';
    import infoModal  from '@/pages/cms-common/model'
    import programModal  from '../../program/push/select'
    import { exportExcelFile } from '@/utils';
    import detailsForm from './check';
    import checkDialog from './checkDialog';
    import { findPageForFirstCheck,exportPlanFirstCheckExcel,batchCheck } from '@/api/cms-api/projectOperating/plan';
    import * as types from '@/api/cms-api/projectOperating/plan/types';
    import { getBigMarketType, getSmallMarketType } from '@/api/cms-api/projectOperating/plan/index';

    export default {
        mixins: [dictionary,region],
        components:{
            detailsForm,
            checkDialog,
            infoModal,
            programModal,
            dealerMadal
        },
        data(){
            return {
                columns: this.creatColumns(),
                fetchApi: findPageForFirstCheck,
                fetchParams: {},
                visible: false,
                visibleDrawer:false,
                visibleDialog:false,
                visibleDialogPro:false,
                visibleDealer: false,
                initDealerData:[],
                detailsConfig:{},
                topFilterInit: this.creatTopFilterList(),
                selectedRows: [], //选中内容
                submitData:{},   //批量审核内容
                modelIdList:[],
                modelName:"",
                projectProgramId:0, //项目id,
                dealerCode:"",
                dealerName:"",
                orgId: null, //登录人所属组织
                dealerType: '25381001,25381002,25381003,25381004,25381005' //不包含大客户的
            }
        },
        mounted(){
            //初始化项目大类
            this.initBigMarketType();
            //初始化当前登录用户
            // this.getUserInfo();
            this.BaseTable = this.$refs.table.$refs.pageTable;
        },
        methods:{
            async getUserInfo() {
                this.loginUser = await getLoginUser({});
                if (this.loginUser != null && this.loginUser != undefined) {
                    if (this.loginUser.data.orgType == 15061005) {
                    //是事业部
                    this.orgId = this.loginUser.data.orgId;
                    }
                    // if (this.loginUser.data.orgType == 15061007) {
                    //办事处 获取父类ID，赋给orgId
                    // this.orgId = this.loginUser.data.orgId;
                    // }
                }
            },
            //选中
            selectChange(rows) {
                this.selectedRows = rows;
                console.log(this.selectedRows);
            },
            //取项目大类
            async initBigMarketType() {
                let res = [];
                let rd = await getBigMarketType();
                for (let i in rd.data) {
                    res.push({ text: rd.data[i].typeName, value: rd.data[i].typeId });
                }
                this.topFilterInit[6].itemList = res;
            },
            //取项目小类
            async initMarketTypeSmall(parentTypeId) {
                let res = [];
                this.dataParams = { parentTypeId: parentTypeId };
                let rd = await getSmallMarketType(this.dataParams);
                for (let i in rd.data) {
                    res.push({ text: rd.data[i].typeName, value: rd.data[i].typeId });
                }
                this.topFilterInit[7].itemList = res;
            },
            //车型弹窗打开
            openModelDialog() {
                this.visibleDialog = true;
            },
            //车型清空
            clearSelectModel() {
                //清空数据
                this.modelIdList = '';
                this.modelName ='';
                //清空车型名称
                this.topFilterInit.find(item => item.fieldName === 'modal').initialValue='';
            },
             //车型弹窗关闭
            selectModelBack(data) {
                if(data && data.data && typeof(data.data)!=null){
                    //清空数据
                    this.modelIdList = '';
                    this.modelName ='';
                    //循环返回数据
                    data.data.forEach(x => {
                        //使用逗号分隔拼接车型ID
                        if(this.modelIdList==""){
                            this.modelIdList = x.modelId;
                        }else{
                            this.modelIdList += "," + x.modelId;
                        }

                        //使用逗号分隔拼接车型名称
                        if(this.modelName==""){
                            this.modelName = x.modelName;
                        }else{
                            this.modelName += "," + x.modelName;
                        }
                    });

                    //显示车型名称
                    this.topFilterInit[5].initialValue = this.modelName;
                }

                this.visibleDialog =false; //关闭弹窗
            },
            //项目弹窗打开
            openModelDialogPro() {
                this.visibleDialogPro = true;
            },
            //项目清空
            clearSelectModelPro() {
                //清空项目id
                 this.projectProgramId = '';
                //清空项目名称
                this.topFilterInit.find(item => item.fieldName === 'projectProgramName').initialValue='';
            },
            //项目弹窗关闭
            selectModelBackPro(data) {
                if(data && data.data && typeof(data.data)!=null){
                    this.projectProgramId = data.data[0].projectProgramId;

                    this.topFilterInit[8].initialValue = data.data[0].programName;

                }

                this.visibleDialogPro =false; //关闭弹窗
            },
            // 经销商打开窗口 -传数据
            dealerHandle() {
                //TODO 经销商信息查询界面只显示本事业部下属的单一销售、4S店类型的经销商；
                this.initDealerData={
                    excludeBigCustomer:false,//是否查询大客户经销商，如果查询 true，不查询 false
                    id:1001
                }
                this.visibleDealer = true;
            },
            // 经销商清除
            clearDealerHandle() {
                this.dealerCode = '';
                this.dealerName = '';
                this.topFilterInit.find(item => item.fieldName === 'dealerName').initialValue='';
            },
            // 经销商关闭窗口 -返回数据
            closeDealer(data) {
                if(data.data&&data.data.length>0){
                    //循环返回数据
                    data.data.forEach(x => {
                        this.dealerCode = x.dealerCode;
                        this.dealerName = x.dealerName;
                    });
                    //显示经销商名称
                    this.topFilterInit[10].initialValue = this.dealerName;
                }
                //关闭弹窗
                this.visibleDealer = data.visible;
            },

            //打开审核意见窗口
            dialogOpen() {
                this.visible = true;
            },
            //关闭审核意见
            dialogClose(data) {
                this.visible = false;
                if(data.type!=null&&data.type=="sure"){ //如果弹窗点击确定
                    if(this.submitData.type == 'reject'){   //如果是批量驳回，则需校验审核意见是否为空
                        if(data.data.reason==null || data.data.reason==""){
                            this.$notify.error({title: '提示信息',message:'请填写审核意见!'});
                            return;
                        }
                    }
                    //提交审核信息
                    this.submitData.reason = data.data.reason;    //审核意见
                    this.batchCheck();
                }
            },
            //打开窗口
            drawerHandle(row,type){
                let id = -1;
                if(type != 'add'){
                    id = row.planId;
                }
                this.detailsConfig = {
                    id: id,  //表主键
                    formType:type
                }
                this.visibleDrawer = true;
            },

            //关闭窗口
            closeDrawer(data){
                this.visibleDrawer = false;
                if (data.type === 'refresh') {
                    // 重新加载表格数据
                    this.fetchParams = { ...this.fetchParams };
                }
            },
            //当搜索按钮按下后会触发
            changeHandle(val){

                if (!val) {
                    val = {planStartDate:[],activityMonth:[]}
                }
                if(!val.modal){
                    this.modelIdList = '';
                }
                if(!val.projectProgramName){
                    this.projectProgramId = '';
                }
                if(!val.dealerName){
                    this.dealerCode = '';
                    this.dealerName = '';
                }
                this.fetchParams = Object.assign({'projectProgramId':this.projectProgramId,"modelIdList":this.modelIdList,"ownerCode":this.dealerCode},
                {
                    planStartDateBegin:val.planStartDate[0]||undefined,
                    planStartDateEnd:val.planStartDate[1]||undefined,
                    activityMonthBegin:val.activityMonth[0]||undefined,
                    activityMonthEnd:val.activityMonth[1]||undefined,
                }, val);
            },
            //展开收起搜索框触发
            collapseHandle(){
                this.$nextTick(() => {
                    this.BaseTable.EXECUTE_RESET_HEIGHT();
                });
            },

            //表格数据变化时
            onCellChange(keys, obj){
                // console.log(keys,obj,"val")
                // console.log(keys[Object.keys(keys)[0]],"修改后对应的编码")
                //根据根据输入的计划批准金额自动计算计划核销比例
                let key = Object.keys(keys)[0];
                let a = key.substring(key.indexOf('|') + 1);
                if (a == 'planApproveAmount') {
                    let planApproveAmount = obj.planApproveAmount.replace(/,/g, "").replace(/\s/g,"");
                    var f = parseFloat((planApproveAmount / obj.planProjectAmount)*100);
                    f=Math.round(f*100)/100;
                    var s = f.toString();
                    var rs = s.indexOf('.');
                    if (rs < 0) {
                        rs = s.length;
                        s += '.';
                    }
                    while (s.length <= rs + 2) {
                        s += '0';
                    }
                    obj.planCancellationRatio = s;
                }
            },
            //批量通过
            batchPass(){
                let rowData = this.selectedRows;
                if(rowData.length==0){
                    this.$notify.error({title: '提示信息',message:'请选择审批记录!'});
                    return;
                }
                let showAlert = false;
                //判断所选择的记录是否已填写
                for(let i=0;i<rowData.length;i++){
                    if(!rowData[i].planApproveAmount){
                        this.$notify.error({title: '提示信息',message:'计划批准金额不能为空!'});
                        return;
                    }
                    if(!rowData[i].planTimeDay){
                        this.$notify.error({title: '提示信息',message:'计划支持场次/投放天数不能为空!'});
                        return;
                    }
                    //如果支持方式为单店支持时，判断计划批准金额是否超过计划项目金额的70%
                    if(rowData[i].cooperationMethod == types.COOPERATION_MODE_SINGLE){
                        let planProjectAmount = rowData[i].planProjectAmount.replace(/,/g, "").replace(/\s/g,"");
                        let planApproveAmount = rowData[i].planApproveAmount.replace(/,/g, "").replace(/\s/g,"");
                        if(parseFloat(planApproveAmount)/parseFloat(planProjectAmount)>0.7){
                            showAlert = true;
                        }
                    }

                }
                if(showAlert){
                    this.$confirm('批准金额超过计划金额的70%，是否确认审核通过?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async() => {

                        this.submitData.type = 'pass';  //通过
                        this.dialogOpen();

                    }).catch(() => {});
                    return;
                }

                this.submitData.type = 'pass';  //通过
                this.dialogOpen();
            },
            //批量驳回
            batchReject(){
                console.log("this.selectedRows:",this.selectedRows);
                let rowData = this.selectedRows;
                if(rowData.length==0){
                    this.$notify.error({title: '提示信息',message:'请选择审批记录!'});
                    return;
                }
                //判断所选择的记录是否已填写
                for(let i=0;i<rowData.length;i++){
                    if(!rowData[i].planApproveAmount){
                        this.$notify.error({title: '提示信息',message:'计划批准金额不能为空!'});
                        return;
                    }
                    if(!rowData[i].planTimeDay){
                        this.$notify.error({title: '提示信息',message:'计划支持场次/投放天数不能为空!'});
                        return;
                    }
                }
                this.submitData.type = 'reject';  //驳回
                this.dialogOpen();
            },
            //批量审核提交
            async batchCheck(){
                this.submitData.data = Object.assign( [],this.selectedRows);;   //填充数据
                console.log("this.submitData:",this.submitData);
                //循环去掉数字中的逗号
                for(let i=0;i<this.submitData.data.length;i++){
                    this.submitData.data[i].planApproveAmount = this.submitData.data[i].planApproveAmount.replace(/,/g, "").replace(/\s/g,"");
                }
                let res ;
                //提交
                res = await batchCheck(this.submitData);
                if (res.resultCode === 200) {
                    this.$notify.success({title: '提示信息',message:'保存成功!'});
                    // 重新加载表格数据
                    this.fetchParams = { ...this.fetchParams };
                }else {
                    this.$notify.error({title: '提示信息',message:res.errMsg||'保存失败!'});
                }
            },
            //创建搜索配置
            creatTopFilterList(){
                return [
                    { type: 'INPUT', label: '项目编号', fieldName: 'planCode', placeholder: '请输入' },
                    { type: 'INPUT', label: '项目名称', fieldName: 'projectName', placeholder: '请输入' },
                    { type: 'RANGE_DATE', label: '项目开始日期', fieldName: 'planStartDate', placeholder: '请输入' },
                    { type: 'RANGE_DATE', label: '项目月份', fieldName: 'activityMonth', dateType: 'monthrange', initialValue: '', placeholder: '请选择' },
                    { type: 'SELECT', label: '项目状态', fieldName: 'planStatus', placeholder: '请选择', itemList: this.createDictListRemoveCodes('2531',[types.DEALER_PROJECT_STATUS_PLAN_NOT_SUBMIT,
                            types.DEALER_PROJECT_STATUS_PLAN_EXAMINE_FIRST_PASS,
                            types.DEALER_PROJECT_STATUS_PLAN_EXAMINE_LAST_PASS,
                            types.DEALER_PROJECT_STATUS_PLAN_EXAMINE_REJECT,
                            types.DEALER_PROJECT_STATUS_PLAN_EXAMINE_REFUSE,
                            types.DEALER_PROJECT_STATUS_SUMMARY_NOT_SUBMIT,
                            types.DEALER_PROJECT_STATUS_SUMMARY_SUBMIT,
                            types.DEALER_PROJECT_STATUS_SUMMARY_EXAMINE_FIRST_PASS,
                            types.DEALER_PROJECT_STATUS_SUMMARY_EXAMINE_REJECT,
                            types.DEALER_PROJECT_STATUS_SUMMARY_EXAMINE_REFUSE,
                            types.DEALER_PROJECT_STATUS_ACTIVITY_END,
                            types.DEALER_PROJECT_STATUS_CANCEL])},
                    { type: 'INPUT', label: '车型', fieldName: 'modal', placeholder: '请选择' ,readonly:true,
                        unitRender: () => {
                            return (
                                <div>
                                    <el-button slot="append" icon="el-icon-search" onClick={() =>this.openModelDialog()}></el-button>
                                    <el-button slot="append" icon="el-icon-delete" onClick={() => this.clearSelectModel()}></el-button>
                                </div>
                            );
                        }
                    },
                    { type: 'SELECT',
                        label: '项目大类',
                        fieldName: 'projectMainClass',
                        placeholder: '请选择',
                        initialValue: '',
                        itemList: [],
                        change: value => {
                            this.initMarketTypeSmall(value);
                        }
                    },
                    { type: 'SELECT', label: '项目小类', fieldName: 'projectSmallClass', placeholder: '请选择', initialValue: '', itemList: [] },
                    { type: 'INPUT', label: '项目方案', fieldName: 'projectProgramName', placeholder: '请选择' ,readonly:true,
                        unitRender: () => {
                            return (
                                <div>
                                    <el-button slot="append" icon="el-icon-search" onClick={() =>this.openModelDialogPro()}></el-button>
                                    <el-button slot="append" icon="el-icon-delete" onClick={() => this.clearSelectModelPro()}></el-button>
                                </div>
                            );
                        }
                    },
                    { type: 'SELECT', label: '合作方式', fieldName: 'cooperationMethod', placeholder: '请选择',  itemList: this.createDictList('2532')},
                    {
                      type: 'INPUT',
                        label: '经销商名称',
                        fieldName: 'dealerName',
                        placeholder: '请选择',
                        initialValue: '',
                        readonly:true,
                        unitRender: () => {
                            return (
                                <div>
                                    <el-button slot="append" icon="el-icon-search" onClick={() =>this.dealerHandle()}></el-button>
                                    <el-button slot="append" icon="el-icon-delete" onClick={() => this.clearDealerHandle()}></el-button>
                                </div>
                            );
                        }
                    },
                ];
            },
            //导出
            async doExportExcel(){
                // this.$refs.topFilterRef.SUBMIT_FORM();

                this.$refs.commonTopFilter.excuteFormData(this.$refs.commonTopFilter.form);
                let subForm = this.$refs.commonTopFilter.form;
                subForm.statusQuery = types.DEALER_PROJECT_STATUS_PLAN_SUBMIT;
                this.fetchParams = Object.assign({'projectProgramId':this.projectProgramId,"modelIdList":this.modelIdList,"ownerCode":this.dealerCode},
                {
                    modelIdList:this.modelIdList,
                    ownerCode:this.dealerCode,
                    planStartDateBegin:subForm.planStartDate[0]||undefined,
                    planStartDateEnd:subForm.planStartDate[1]||undefined,
                    activityMonthBegin:subForm.activityMonth[0]||undefined,
                    activityMonthEnd:subForm.activityMonth[1]||undefined,
                }, subForm);
                exportPlanFirstCheckExcel(this.fetchParams).then(res => {
                    exportExcelFile(res.data,"项目计划审核");
                });
            },
            //创建表格列配置
            creatColumns(){
                return [
                    { title: '操作', dataIndex: 'column-action', width: 100, fixed: 'left',
                        render: (props, h) => {
                            return (
                                <div>
                                    <el-button size="mini" type="text" onClick={() => this.drawerHandle(props.row,'edit')}>
                                        审核
                                    </el-button>
                                </div>
                            );
                        }
                    },
                    { title: '序号', dataIndex: 'index', fixed:"left", width: 80, sorter: true,
                        render: props => {
                            return <span>{props.row.index + 1}</span>;
                        }
                    },
                    {
                        title: '计划批准金额',
                        dataIndex: 'planApproveAmount',
                        sorter: true,
                        editable: true,
                        defaultEditable: true,
                        editType: 'number',
                        editRequired:true,
                        precision:2,
                        max:99999999,
                        numberFormat:true,
                    },
                    { title: '计划项目金额', dataIndex: 'planProjectAmount', sorter: true,numberFormat:true,},
                    { title: '计划核销比例', dataIndex: 'planCancellationRatio',sorter: true,
                        render: props => {
                            return <span>{props.row.planCancellationRatio}%</span>;
                        }
                    },
                    { title: '项目月份', dataIndex: 'activityMonth',sorter: true, dateFormat: 'YYYY年MM月'},
                    { title: '预算类别', dataIndex: 'budgetType',  sorter: true,
                        render: props => {
                        //编码转汉字
                        return <span>{this.createDictText(props.row.budgetType, '8052')}</span>;
                    } },
                    { title: '方案名称', dataIndex: 'programName', sorter: true },
                    { title: '项目编号', dataIndex: 'planCode', sorter: true},
                    { title: '事业部', dataIndex: 'orgName', sorter: true },

                    {
                    title: '省份',
                    dataIndex: 'provinceId',
                    sorter: true,
                    render: props => {
                        return <span>{this.createRegionText(props.row.provinceId)}</span>;
                    }
                    },
                    {
                    title: '城市',
                    dataIndex: 'cityId',
                    sorter: true,
                    render: props => {
                        return <span>{this.createRegionText(props.row.cityId)}</span>;
                    }
                    },
                    { title: '经销商代码', dataIndex: 'ownerCode', sorter: true },
                    { title: '经销商名称', dataIndex: 'dealerName', sorter: true },
                    // { title: '项目大类', dataIndex: 'projectMainClass', sorter: true },
                    { title: '项目大类', dataIndex: 'projectMainClassName', sorter: true },
                    // { title: '项目小类', dataIndex: 'projectSmallClass', sorter: true },
                    { title: '项目小类', dataIndex: 'projectSmallClassName', sorter: true },
                    { title: '项目名称', dataIndex: 'projectName', sorter: true},
                    { title: '项目地点', dataIndex: 'planProjectLocation', sorter: true},
                    { title: '项目介绍（项目描述）', dataIndex: 'projectDesc', sorter: true},
                    { title: '项目车型', dataIndex: 'modelLists', sorter: true},
                    { title: '计划开始日期', dataIndex: 'planStartDate', sorter: true, dateFormat: 'YYYY年MM月DD日'},
                    { title: '计划结束日期', dataIndex: 'planEndDate', sorter: true, dateFormat: 'YYYY年MM月DD日'},
                    {
                        title: '计划支持场次、天数',
                        dataIndex: 'planTimeDay',
                        sorter: true,
                    },
                    {
                        title: '合作方式',
                        dataIndex: 'cooperationMethod',
                        sorter: true,
                        render: props => {
                            //编码转汉字
                            return <span>{this.createDictText(props.row.cooperationMethod, '2532')}</span>;
                        }
                    },
                    { title: '目标集客', dataIndex: 'targetGuestsNum', sorter: true},
                    { title: '目标留档', dataIndex: 'targetRetentionNum', sorter: true},
                    { title: '目标订单', dataIndex: 'targetOrderNum', sorter: true},
                    { title: '场地（室内/室外）+面积', dataIndex: 'planProjectSite', sorter: true},
                    { title: '展位计划金额', dataIndex: 'planBoothAmount', sorter: true},
                    { title: '展位批准金额', dataIndex: 'realBoothAmount', sorter: true},
                    { title: '搭建运营计划金额', dataIndex: 'planBuildAmount', sorter: true},
                    { title: '搭建运营批准金额', dataIndex: 'realBuildAmount', sorter: true}
                ];
            },
        },
    }
</script>

<style scoped>

</style>
